<script setup>
// import {
//   requiredValidator,
// } from '@validators'
import { onMounted, onUnmounted, ref, watch } from 'vue'

const props = defineProps({
  isDrawerOpen: {
    type: Boolean,
    required: true,
  },
  operType: {
    type: Number,
    required: true,
    default: 0,
  },
  currRow: Object,
  currOption: Object,
  datasourceOption: Object,
})

const emit = defineEmits([
  'update:isDrawerOpen',
  'addData',
  'updateData',
])

const operType = ref(props.operType)
const currRow = ref(props.currRow)
const option = ref(props.currOption)
const datasourceOptionList = reactive(props.datasourceOption)
const row = currRow.value
const isFormValid = ref(false)
const refForm = ref()
const title = ref(operType.value == 0 ? '新增管理器':'更新管理器')

// 表单数据
const id = ref(row.id || '')
const datasourceId = ref(row.datasourceId || '')
const dbStyle = ref(row.dbStyle || '')
const type = ref(row.type || 'single')
const smBeanName = ref(row.smBeanName || '')
const smName = ref(row.smName || '')
const smDesc = ref(row.smDesc || '')
const sqlInterceptors = ref(row.sqlInterceptors || '')
const sqlInterceptorArr = reactive(sqlInterceptors.value.split(",") || [])
const slaveDatasourceIds = ref(row.slaveDatasourceIds || '')
const slaveDatasourceIdArr = reactive(slaveDatasourceIds.value.split(",").map(Number) || [])
const nameConversion = ref(row.nameConversion || '')
const offsetStartZero = ref(row.offsetStartZero || '')
const disabled = ref(row.disabled)

onMounted(() => {
  changeType(type.value)
})

onUnmounted(() => {

})

watch(type, val => {
  changeType(val)
})

const showSingle = ref(true)
const showMasterSlave = ref(false)

const changeType = val => {
  if(val == 'single'){
    showSingle.value = true
    showMasterSlave.value = false
  }else{
    showSingle.value = false
    showMasterSlave.value = true
  }
}

// 👉 drawer close
const closeNavigationDrawer = () => {
  emit('update:isDrawerOpen', false)
  nextTick(() => {
    refForm.value?.reset()
    refForm.value?.resetValidation()
  })
}

const onSubmit = () => {
  refForm.value?.validate().then(({ valid }) => {
    if(valid) {
      const data = {
        id: id.value,
        datasourceId: datasourceId.value,
        dbStyle: dbStyle.value,
        type: type.value,
        smBeanName: smBeanName.value,
        smName: smName.value,
        smDesc: smDesc.value,
        sqlInterceptors: sqlInterceptorArr.join(','),
        slaveDatasourceIds: slaveDatasourceIdArr.join(','),
        nameConversion: nameConversion.value,
        offsetStartZero: offsetStartZero.value,
        disabled: disabled.value,
      }

      if(operType.value == 0){
        emit('addData', data)
      }else{
        emit('updateData', data)
      }
      
      emit('update:isDrawerOpen', false)
      nextTick(() => {
        refForm.value?.reset()
        refForm.value?.resetValidation()
      })
    }
  })
}

const handleDrawerModelValueUpdate = val => {
  emit('update:isDrawerOpen', val)
}
</script>

<template>
  <VNavigationDrawer
    temporary
    style="inline-size: 1120px;"
    location="end"
    class="scrollable-content"
    :model-value="props.isDrawerOpen"
    @update:model-value="handleDrawerModelValueUpdate"
  >
    <AppDrawerHeaderSection
      :title="title"
      @cancel="closeNavigationDrawer"
    />

    <!-- <PerfectScrollbar :options="{ wheelPropagation: false }"> -->
    <VCard
      flat
      style="overflow-y: auto;"
    >
      <VCardText>
        <VForm
          ref="refForm"
          v-model="isFormValid"
          @submit.prevent="onSubmit"
        >
          <VRow>
            <VCol cols="12">
              <VTextField
                v-model="smBeanName"
                :rules="[requiredValidator]"
                class="setting-mb-12"
                label="Bean名称"
                clearable
              />
            </VCol>

            <VCol cols="12">
              <VTextField
                v-model="smName"
                :rules="[requiredValidator]"
                class="setting-mb-12"
                label="sql管理器中文名称"
                clearable
              />
            </VCol>

            <VCol cols="12">
              <VTextField
                v-model="smDesc"
                :rules="[requiredValidator]"
                class="setting-mb-12"
                label="描述信息"
                clearable
              />
            </VCol>

            <VCol cols="12">
              <VAutocomplete
                v-model="dbStyle"
                label="数据库类型"
                :items="option.dbStyle.list"
                clearable
                clear-icon="tabler-x"
                item-title="title"
                item-value="value"
              />
            </VCol>

            <VCol cols="12">
              <VAutocomplete
                v-model="type"
                label="管理器类型"
                :items="option.type.list"
                clearable
                clear-icon="tabler-x"
                item-title="title"
                item-value="value"
              />
            </VCol>

            <VCol
              v-if="showSingle"
              cols="12"
            >
              <VAutocomplete
                v-model="datasourceId"
                label="数据源ID"
                :items="datasourceOptionList"
                clearable
                item-title="dsName"
                item-value="id"
              />
            </VCol>

            <VCol
              v-if="showMasterSlave"
              cols="12"
            >
              <VAutocomplete
                v-model="datasourceId"
                label="主库数据源（更新操作走主库）"
                :items="datasourceOptionList"
                clearable
                item-title="dsName"
                item-value="id"
              />
            </VCol>

            <VCol
              v-if="showMasterSlave"
              cols="12"
            >
              <VAutocomplete
                v-model="slaveDatasourceIdArr"
                label="从库数据源（查询操作走从库）"
                :items="datasourceOptionList"
                multiple
                clearable
                item-title="dsName"
                item-value="id"
              />
            </VCol>

            <VCol cols="12">
              <VAutocomplete
                v-model="sqlInterceptorArr"
                label="sql拦截器"
                :items="option.sqlInterceptors.list"
                multiple
                clearable
                clear-icon="tabler-x"
                item-title="title"
                item-value="value"
              />
            </VCol>

            <VCol cols="12">
              <VAutocomplete
                v-model="nameConversion"
                label="命名风格"
                :items="option.nameConversion.list"
                clearable
                clear-icon="tabler-x"
                item-title="title"
                item-value="value"
              />
            </VCol>

            <VCol cols="12">
              <VCheckbox
                v-model="offsetStartZero"
                class="setting-mb-12"
                label="分页是否从0开始"
              />
            </VCol>

            <VCol cols="12">
              <VCheckbox
                v-model="disabled"
                class="setting-mb-12"
                label="是否禁用"
              />
            </VCol>

            <VCol cols="6">
              <VBtn
                type="submit"
                class="me-3 w-100"
              >
                提交
              </VBtn>
            </VCol>
            <VCol cols="6">
              <VBtn
                class="w-100"
                type="reset"
                variant="tonal"
                color="secondary"
                @click="closeNavigationDrawer"
              >
                取消
              </VBtn>
            </VCol>
          </VRow>
        </VForm>
      </VCardText>
    </VCard>
    <!-- </PerfectScrollbar> -->
  </VNavigationDrawer>
</template>

<style scoped>
.w-100 {
  inline-size: 100%;
}
</style>
